<?php
include_once "baseChannel.php";

class lexiang extends baseChannel {
    public $mchid;
    public $apikey;

    public function __construct($setting){
        parent::__construct($setting);
        $this->mchid = $setting['mchid'];
        $this->apikey = $setting['apikey'];
    }
    /*通用签名方法*/
    public function getSign($params){
        unset($params['sign']);
        ksort($params);
        $params['key'] = $this->apikey;
        $str = http_build_query($params);
        return strtoupper(md5($str));
    }
    /*查询余额*/
    public function queryBalance($params=[]){
        $url = $this->query_balance_url;
        $post_data = [
            'mchid'=>$this->mchid,
            'time' => $this->timestamp
        ];

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url,'POST',$post_data);
        $return_data = json_decode($return_str,1);
        if($return_data['error'] == 0){
            return [
                'error'=>0,
                'msg'=>'查询成功',
                'balance'=> $return_data['fBalance'] ?? 0, //余额
                'credit'=> $return_data['fCredit'] ?? 0, //授信
                'code'=>200
            ];
        }
        return [
            'error'=>1,
            'msg'=>$return_data['szRtnCode'] ?? '查询失败',
            'code'=>500
        ];

    }
    public function queryProduct($params=[]){
        return [
            'error'=>-1,
            'msg'=>'不支持queryProduct',
            'code'=>500
        ];
    }
    public function queryOrder($params){
        $url = $this->query_order_url;
        $post_data = [
            'appid'=>$this->appid,
            'user_order_sn'=>$params['user_order_sn'],
        ];
        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url,'POST',$post_data);
        $return_data = json_decode($return_str,1);

        $ret = [
            'error'=>0,
            'order_status' => 2,
            'msg'=>'初始化',
            'pz' => $return_data['szRtnMsg'] ?? '', //凭证
            'post_data'=> json_encode($post_data), //提交字符串
            'channel_data'=> $return_str, //返回字符串
            'code' => 200
        ];
        //充值中
        if($return_data['nRtn'] == 5011 || $return_data['nRtn'] == 5019){
            $ret['msg'] = '充值中:'.$return_data['szRtnCode'];
        }
        // 成功
        if($return_data['nRtn'] == 5012){
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '充值完成:'.$return_data['szRtnCode'];
        }
        // 失败
        if($return_data['nRtn'] == 5013){
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '充值失败:'.$return_data['szRtnCode'];
        }
        // 不存在订单
        if($return_data['nRtn'] == 5005){
            $ret['error'] = 1;
            $ret['code'] = 404;
            $ret['order_status'] = -1;
            $ret['msg'] = '订单不存在:'.$return_data['szRtnCode'];
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params=[]){
        $url = $this->submit_order_url;
        $post_data = [
            'szAgentId'=>$this->szAgentId,
            'szOrderId'=>$params['user_order_sn'],
            'szPhoneNum' => $mobile,
            'nMoney' => $code,
            'nSortType' => $params['isp'],
            'nProductClass' => 1,
            'nProductType' => 1,
            'szTimeStamp' => date("Y-m-d H:i:s", $this->timestamp),
        ];
        $post_data['szProductId'] = $code;
        $post_data['szNotifyUrl'] = $this->callback_url;

        $sign = $this->getSign($post_data);
        $post_data['sign'] = $sign;


        $return_str = $this->httpRequest($url,'POST',$post_data);
        $return_data = json_decode($return_str,1);

        $ret = [
            'error'=> -1,
            'msg'=>'初始化',
            'channel_order' => $return_data['szSystemId'] ?? '',
            'post_data' => json_encode($post_data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' => $return_data['fSalePrice'] ?? 0,
            'channel_balance' => $return_data['fNBalance'] ?? null,
        ];
        if($return_data['nRtn'] == 0){
            $ret['error'] = 0;
            $ret['msg'] = $return_data['szRtnCode'] ?? '下单成功';
        }
        //下单失败 1006 余额不足
        if( in_array($return_data['nRtn'], [1000, 1001, 1003, 1004, 2001, 2002, 2003, 2020, 2021, 1006, 2030])){
            $ret['error'] = 1;
            $ret['code'] = 500;
            $ret['msg'] = $return_data['szRtnCode'] ?? '下单失败';
        }
        return $ret;
    }

    public function checkCallbackSign($params){
        $post_data = [
            'szAgentId' => $this->szAgentId,
            'szOrderId'=> $params['szOrderId'],
            'szPhoneNum' => $params['szPhoneNum'],
            'nDemo' => $params['nDemo'],
            'fSalePrice' => $params['fSalePrice'],
            'nFlag' => $params['nFlag'],
        ];
        $signStr = http_build_query($post_data);
        $signStr = $signStr."&szKey=".$this->apikey;
        $signStr = urldecode($signStr);
        $sign = md5($signStr);
        return $sign;
    }
    public function callback($params){
        $this->callback_params = $params;
        $this->channel_order_sn = trim($params['szSystemId']);
        $this->push_order_sn = $params['szOrderId'];
        //返回参数
        $res = $this->initCallBackParam();
        //订单状态
        $order_status = $params['nFlag'];
        $msg = $order_status;
        //凭证
        $pz = $params['szRtnMsg'];


        $sign = $this->checkCallbackSign($params);

        if($sign != $params['sign']){
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            return $res;
        }

        if($order_status==2){
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
        }

        if($order_status==3){
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
        }
        return $res;
    }
}
/*
$obj = new demo([
    'szAgentId' => '444444444444',
    'apikey' => '44444444444444444',
    'callback_url' => 'http://api.agent.recharge.bx10086.cn/v2/balance',
    'query_balance_url' => 'http://api.agent.recharge.bx10086.cn/v2/balance',
    'query_order_url' => 'http://api.agent.recharge.bx10086.cn/v2/recharge/query',
    'submit_order_url' => 'http://api.agent.recharge.bx10086.cn/v2/recharge',
]);*/

//$res = $obj->queryBalance();

//$res = $obj->queryOrder([
//    'user_order_sn' => '1641569132'
//]);

/*
$res = $obj->submitOrder('13530207720','9000',[
    'push_order_sn' => time(),
    'isp' => 1
]);
*/

//var_dump($res);
